﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Entity;
using UDS.Components;

namespace UDS.WebApp.SubModule
{
    public partial class UpdateFilePage : CFPageBase
    {
        protected int FileID
        {
            get;
            private set;
        }

        protected CFFileInfo FileInfo
        {
            get;
            private set;
        }

        /// <summary>
        /// The user must have the "ManageCommonFile" permission.
        /// </summary>
        public override PermissionType RequiredPermission
        {
            get { return PermissionType.ManageCommonFile; }
        }

        protected override void OnInit(EventArgs e)
        {
            // Hook event hanlders
            btnUpdateFile.Click += new EventHandler(OnUpdateFileClick);

            // Read/bind data
            FileID = QSUtil.GetPositiveInt32("FileID", 0);
            if (FileID > 0)
            {
                FileInfo = CommonFile.GetFile(FileID);
            }

            if (FileInfo == null)
            {
                SiteContext.Current.AlertAndRedirect("指定文件并不存在。", "FileList.aspx");
            }
            else
            {
                // Set initial value
                txtName.Text = FileInfo.Name;
                txtVersion.Text = FileInfo.Version;
                listCatalog.SelectedCatalog = FileInfo.CatalogID;
                cbInvalid.Checked = FileInfo.Invalid;

                phOldFile.Visible = false;
                if (!string.IsNullOrEmpty(FileInfo.VPath))
                {
                    phOldFile.Visible = true;
                    linkOldFile.Text = HttpUtility.HtmlEncode(FileInfo.DownloadablePath);
                    linkOldFile.NavigateUrl = FileInfo.DownloadablePath;
                }
            }

            base.OnInit(e);
        }

        private void OnUpdateFileClick(object sender, EventArgs e)
        {
            FileInfo.Name = txtName.Text;
            FileInfo.Version = txtVersion.Text;
            FileInfo.CatalogID = listCatalog.SelectedCatalog;
            FileInfo.Invalid = cbInvalid.Checked;
            FileInfo.Creator = SiteContext.Current.UserName;

            try
            {
                CommonFile.UpdateFile(FileInfo, fileUpload.PostedFile);
                SiteContext.Current.AlertAndRedirect("成功更新文件：" + FileInfo.Name + "。", "FileList.aspx");
            }
            catch (Exception ex)
            {
                SiteContext.Current.AlertAndRedirect("更新文件失败：" + ex.Message, "FileList.aspx");
            }
        }
    }
}
